package com.yeban.javase.day11.test01;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/10/20
 */
public class PokerCards {

    private static List<Card> cards = new ArrayList<>();

    public PokerCards() {
    }

    // 做牌
    static {
        String[] suits  = {"♠", "♥", "♣", "♦"};
        String[] ranks  = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
        // 添加大小王
        cards.add(new Card("","Big Joker",0));
        cards.add(new Card("","Little Joker",1));
        int index = 2;      // 对应扑克牌索引
        for (String s : suits ) { // 遍历花色
            for (String r : ranks ) {    // 遍历牌面等级
                cards.add(new Card(s, r, index++));
                //index++;
            }
        }
    }

    // 乱序洗牌
    public List<Card> getShuffledCards() {
        Collections.shuffle(cards);
        return cards;
    }

    // 发牌(获取当前元素的)
    public List<Card> getPokers(List<Card> playerCard1, List<Card> playerCard2, List<Card> playerCard3) {
        // 确保玩家牌为空（防止重复追加）
        playerCard1.clear();
        playerCard2.clear();
        playerCard3.clear();

        // 每次发牌先洗
        Collections.shuffle(cards);

        int total = cards.size();   // 54涨
        int n = total - 3; // 51 张要分发

        // 根据索引分发
        for(int i = 0; i < n; i ++) {
            Card c = cards.get(i);  // 当前
            int count = i % 3;  // 发给谁
            if(count == 0) playerCard1.add(c);
            else if(count == 1) playerCard2.add(c);
            else playerCard3.add(c);
        }

        // 底牌bottonCards： subList(total-3, total) 用于获取索引区间的子集合
        List<Card> bottonCards = new ArrayList<>(cards.subList(total - 3, total));
        boolean flag = false;

        // 检查底牌中是否有大王
        for(Card c : bottonCards) {
            if(c.getValue().equals("Big Joker")) {
                flag = true;
                break;
            }
        }

        // 如果大王在底牌，重新发牌
        if(flag) {
            getPokers(playerCard1, playerCard2, playerCard3);
        }

        // 对各个玩家的牌进行排序
        Collections.sort(playerCard1);
        Collections.sort(playerCard2);
        Collections.sort(playerCard3);

        return bottonCards;
    }

    public int whoFirst(List<Card> playerCard1, List<Card> playerCard2, List<Card> playerCard3) {
        for(int i = 0; i < playerCard1.size(); i ++) {
            if(playerCard1.get(i).getValue().equals("Big Joker")) {
                return 1;
            } else if (playerCard2.get(i).getValue().equals("Big Joker")) {
                return 2;
            } else if (playerCard3.get(i).getValue().equals("Big Joker")){
                return 3;
            }
        }
        return -1;
    }
}
